<template>
  <div>
    <div align="right">
      <a-button type="primary" status="warning" @click="nextStep('4')" size="small">上一步</a-button>
      <a-button type="primary" style="margin-left: 20px;" @click="nextStep('6')" size="small">下一步</a-button>
    </div>

    <a-form ref="SettlementbankaccountFromRef" :model="mainForm">
      <a-form-item field="account_info.bank_account_type" label="账户类型" :rules="[REQUIRED]">
        <a-select :style="{ width: '280px' }" v-model="mainForm.account_info.bank_account_type" placeholder="请选择账户类型">
          <a-option value="74">对公账户</a-option>
          <a-option value="75">对私账户</a-option>
        </a-select>
      </a-form-item>
      <a-form-item field="account_info.account_bank" label="开户银行" :rules="[REQUIRED]">
        <a-input style="width: 400px;" v-model="mainForm.account_info.account_bank" disabled />
        <a-button style="margin-left: 10px;" type="primary" @click="searchBank">选择</a-button>
        <template #extra>
          <div>
            <p>1、17家直连银行，请根据<a-link @click="bakRules()" :hoverable="false" style="font-size: 12px;">对照表</a-link>直接填写银行名 ;</p>
            <p>2、非17家直连银行，该参数请填写为“其他银行”。</p>
          </div>
        </template>
      </a-form-item>
      <a-form-item field="account_info.bank_address_code" label="省市编码" :rules="[REQUIRED]">
        <a-input style="width: 400px;" v-model="mainForm.account_info.bank_address_code" placeholder="请输入省市编码"/>
        <template #extra>
          <div>
            <p>至少精确到市，详细参见<a-link @click="numRules()" :hoverable="false" style="font-size: 12px;">省市区编号对照表</a-link>。</p>
            <p style="color: #f00;">注：仅当省市区编号对照表中无对应的省市区编号时，可向上取该银行对应市级编号或省级编号。</p>
          </div>
        </template>
      </a-form-item>
      <a-form-item field="account_info.account_name" label="开户名称" :rules="[REQUIRED]">
        <a-input style="width: 400px;" v-model="mainForm.account_info.account_name" placeholder="请输入开户名称"/>
      </a-form-item>
      <a-form-item field="account_info.bank_branch_id" label="联行号">
        <a-input style="width: 400px;" v-model="mainForm.account_info.bank_branch_id" placeholder="请输入联行号"/>
        <template #extra>
          <div>
            <p>1、17家直连银行无需填写，如为其他银行，则全称（含支行）和联行号二选一。</p>
            <p>2、详细参见<a-link @click="bankNameRules()" :hoverable="false" style="font-size: 12px;">全称（含支行）对照表</a-link>。</p>
          </div>
        </template>
      </a-form-item>
      <a-form-item field="account_info.bank_name" label="全称（含支行）">
        <a-input style="width: 400px;" v-model="mainForm.account_info.bank_name" disabled />
        <a-button style="margin-left: 10px;" type="primary" @click="searchBank">选择</a-button>
        <template #extra>
          <div>
            <p>1、17家直连银行无需填写，如为其他银行，则全称（含支行）和 联行号二选一。</p>
            <p>2、详细参见<a-link @click="bankNameRules()" :hoverable="false" style="font-size: 12px;">全称（含支行）对照表</a-link>。</p>
          </div>
        </template>
      </a-form-item>
      <a-form-item field="account_info.account_number" label="银行账号" :rules="[REQUIRED]">
        <a-input style="width: 400px;" v-model="mainForm.account_info.account_number" placeholder="请输入银行账号"/>
        <template #extra>
          <div>
            <p>数字，长度遵循系统支持的<a-link @click="backNumRules()" :hoverable="false" style="font-size: 12px;">卡号长度要求表</a-link>。</p>
          </div>
        </template>
      </a-form-item>
    </a-form>

    <a-modal v-model:visible="showBankList" :width="700" title="选择银行" @cancel="showBankList = false">
      <div>
        <a-Form>
          <a-form-item>
            <a-radio-group v-model:model-value="choiceBankType" style="margin-bottom: 20px">
              <a-radio :value="1">17家直连银行</a-radio>
              <a-radio :value="0">非17家直连银行</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item label="选择地区">
            <a-cascader :options="cityData" :style="{ width: '260px' }" v-model:model-value="cityCode" allow-clear :path-mode="true" ></a-cascader>
          </a-form-item>
          <div  v-if="choiceBankType === 1">
            <a-form-item label="选择银行">
              <a-radio-group v-model:model-value="choiceBank" style="margin-bottom: 20px">
                <a-radio value="0">对公银行</a-radio>
                <a-radio value="1">对私银行</a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item>
              <div>
                <a-input style="width: 400px;" v-model="searchBankName" :placeholder="`请输入搜索${choiceBank === '0' ? '对公' : '对私'}银行`"/>
                <div class="bank-list">
                  <div v-for="(item, index) in bankData" class="bank-item" :key="index">
                    <div>{{ item.bank_alias }}</div>
                    <div>
                      <a-button size="small" :type="choiceBankData.bank_alias===item.bank_alias?'primary':'dashed'" @click="handlerSearchBank(item)">
                        {{choiceBankData.bank_alias == item.bank_alias ? "已" : "" }}选择
                      </a-button>
                    </div>
                  </div>
                </div>
              </div>
            </a-form-item>
            <a-form-item label="选择支行">
              <div>
                <a-input style="width: 400px;" v-model="searchBranch" :disabled="!enableChoiceBranch"
                         :placeholder="!enableChoiceBranch ? '请先选择地区和银行' : '搜索支行'"/>
                <div class="bank-list">
                  <div v-for="(item, index) in branchBankData" class="bank-item" :key="index">
                    <div>{{ item.bank_branch_name }}</div>
                    <div>
                      <a-button size="small" :type="choiceBranch.bank_branch_id == item.bank_branch_id? 'primary': 'dashed'" @click="handlerBranch(item)">
                        {{choiceBranch.bank_branch_id == item.bank_branch_id ? "已" : "" }}选择
                      </a-button>
                    </div>
                  </div>
                </div>
              </div>
            </a-form-item>
          </div>
          <div v-else>
            <a-form-item label="选择银行">
              其他银行
            </a-form-item>
            <a-form-item label="开户银行行全称（含支行）">
              <a-input style="width: 400px;" v-model="mainForm.account_info.bank_name" />
              <template #extra>
                <div>
                  <p>示例值：施秉县农村信用合作联社城关信用社</p>
                </div>
              </template>
            </a-form-item>
          </div>
        </a-Form>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
  import { onMounted, watch, computed, ref } from 'vue';
  import { REQUIRED, VARCHAR20 } from '@/utils/validator';
  import { useAppStore } from '@/store';
  import { getBankInfo, getPersonalBankInfo, getProvinces, getBranches } from '@/api/shops';

  const appStore = useAppStore();
  const emit = defineEmits(['callbackTab']);
  const props = defineProps({
    submitFrom: {
      type: Object,
      default: () => {},
    }
  });

  const SettlementbankaccountFromRef = ref<any>('');
  const mainForm = ref<any>({
    account_info: {}
  });  // 表单主体内容

  const choiceBankType = ref(1); // 1 17家直连银行 0 非17家直连银行
  const enableChoiceBranch = ref(false);
  const choiceBank = ref("0"); // 0 对公 1 对私
  const picModelFlag = ref(false); // 预览图片显隐
  const selected = ref(""); // 已选数据
  const bankData = ref([]); // 银行数据
  const branchBankData = ref([]);
  const originBankData = ref([]); // 原始银行数据
  const originBranchBankData = ref([]);
  const searchLoading = ref(false);
  const searchBankName = ref("");
  const searchBranch = ref("");
  const bankTotal = ref(0);
  const showBankList = ref(false); // 开户银行弹窗
  const cityData = ref([]); // 地区数据
  const originCityData = ref([]); // 原始地区数据
  const cityCode = ref([]); // 地区编码
  const choiceBankData = ref("");
  const choiceBranch = ref("");
  const itemsPerLoad = ref(1000); // 每次加载的数据条数
  const loadInterval = ref(2000); // 加载数据的间隔时间（毫秒）
  const currentIndex = ref(0); // 当前已加载的数据索引

  const bankList = computed(() => {
    return appStore.bankList;
  });

  // 获取银行列表
  const fetchBankList = async () => {
    let res: any;
    let label: any;
    if (choiceBank.value === "0" && !bankList.value.companyBankList.length) {
      res = await getBankInfo();
      label = "companyBankList";
    } else if (choiceBank.value === "1" && !bankList.value.personalBankList.length) {
      res = await getPersonalBankInfo();
      label = "personalBankList";
    }
    if (res && res.data.success) {
      // 给bankList赋值
    appStore.setBankList({ label, value: res.data.result });
      // 赋值操作
      originBankData.value = res.data.result;
      bankData.value = res.data.result.slice(0, itemsPerLoad.value);
      // 开始定时加载数据 #TODO 感觉不需要一般来说都是直接搜索的不会自己去查找银行所以默认就展示1000个
      // this.setTimeSlowShowBankList();
    } else {
      let key = choiceBank.value === "0" ? "companyBankList" : "personalBankList";
      originBankData.value = bankList.value[key];
      bankData.value = bankList.value[key].slice(0, itemsPerLoad.value);
    }
  };
  // 选择开户银行弹框
  const searchBank = () => {
    showBankList.value = true;
    fetchBankList();
  };
  // 选择开户银行
  const handleBank = () => {

  };
  const bakRules = () => {
    window.open("https://pay.weixin.qq.com/wiki/doc/apiv3_partner/terms_definition/chapter1_1_3.shtml#part-4");
  };
  const numRules = () => {
    window.open("https://pay.weixin.qq.com/wiki/doc/apiv3_partner/terms_definition/chapter1_1_3.shtml");
  };
  const bankNameRules = () => {
    window.open("https://pay.weixin.qq.com/wiki/doc/apiv3_partner/terms_definition/chapter1_1_3.shtml#part-6");
  };
  const backNumRules = () => {
    window.open("https://pay.weixin.qq.com/wiki/doc/apiv3_partner/terms_definition/chapter1_1_3.shtml#part-4");
  };
  // 选择银行
  const handlerSearchBank = (val) => {
    choiceBankData.value = val;
    mainForm.value.account_info.account_bank = val.account_bank;
    mainForm.value.account_info.bank_address_code = val.account_bank_code;
  };
  // 选择支行
  const handlerBranch = (val) => {
    choiceBranch.value = val;
    mainForm.value.account_info.bank_name = val.bank_branch_name;
    mainForm.value.account_info.bank_branch_id = val.bank_branch_id;
  };
  // 模糊搜索 value就是要搜索的内容 data是要搜索的数据
  const deepFind = (value, type) => {
    let str = ["", ...value, ""].join(".*");
    let reg = new RegExp(str);
    if (type == "bank") {
      bankData.value = originBankData.value.filter((item) => reg.test(item.bank_alias));
    } else {
      branchBankData.value = originBranchBankData.value.filter((item) => reg.test(item.bank_branch_name));
    }
  };



  // 上一步/下一步
  const nextStep = (name) => {
    emit("callbackTab", name);
  };
  // 表单校验
  const checkoutForm = async () => {
    const auth = await SettlementbankaccountFromRef.value?.validate();
    if (!auth) {
      return true;
    } else {
      return false;
    }
  };
  // 组件暴露自己的属性
  defineExpose({
    checkoutForm
  });


  // 获取地区
  const fetchProvinces = async() => {
    const res = await getProvinces();
    if (res.data.success) {
      let result = res.data.result.map((item) => {
        return {
          label: item.province_name,
          value: item.province_code + "", // 就这里不转换成string 的话 回显不上去 为此改了3个小时的bug = =
          children: item.citiesList.map((child) => {
            return {
              label: child.city_name,
              value: child.city_code + "",
            };
          }),
        };
      });
      originCityData.value = result;
      cityData.value = result;
    }
  };
  // 获取支行信息
  const fetchBranch = async () => {
    if (cityCode.value.length && choiceBankData.value.bank_alias_code) {
      const res = await getBranches({
        cityCode: cityCode.value[cityCode.value.length - 1],
        bankAliasCode: choiceBankData.value.bank_alias_code,
      });
      if (res.data.success) {
        enableChoiceBranch.value = res. data.result.length ? true : false;
        branchBankData.value = res.data.result;
        originBranchBankData.value = res.data.result

      }
    }
  };

  onMounted(() => {
    fetchProvinces();
  });

  watch(() => props.submitFrom, (val) => {
    mainForm.value = val;
  }, { immediate: true, deep: true });
  // 切换17家银行
  watch(() => choiceBankType.value, (val) => {
    if (val) {
      mainForm.value.account_info.account_bank = '';
    } else {
      // 赋值其他银行数据
      mainForm.value.account_info.bank_branch_id = '';
      mainForm.value.account_info.account_bank = '其他银行';
    }
  }, { deep: true });
  // 搜索支行
  watch(() => searchBranch, (val) => {
    if (val) {
      deepFind(val.value, "branch");
    } else {
      branchBankData.value = originBranchBankData.value;
    }
  }, { deep: true });
  // 搜索银行
  watch(() => searchBankName, (val) => {
    if (val) {
      deepFind(val.value, "bank");
    } else {
      bankData.value = originBankData.value.slice(0, itemsPerLoad.value);
    }
  }, { deep: true });
  // 选择银行
  watch(() => choiceBank, (val) => {
    bankData.value = [];
    setTimeout(() => {
      fetchBankList();
    }, 300);
  }, { deep: true });



  watch(() => cityCode, (val) => {
    if (val && choiceBankData.value && choiceBankData.value.bank_alias_code) {
      fetchBranch();
    }
  }, { deep: true });
  watch(() => choiceBankData, (val) => {
    if (val && cityCode.value.length) {
      fetchBranch();
    }
  }, { deep: true });

</script>

<style scoped lang="less">
  .bank-list {
    margin: 10px 0;
    height: 200px;
    overflow-y: auto;
  }
  .bank-item {
    padding: 16px;
    border-bottom: 1px solid #ededed;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .bank-list {
    margin: 10px 0;
    height: 200px;
    overflow-y: auto;
  }
</style>